from typing import List, Dict

from backend.app.common.log import log
from backend.app.crud.crud_goods import GoodsDao
from backend.app.database.db_es import es_conn
from backend.app.schemas.device import DeviceDetailReq, DeviceInfoSchema
from backend.app.services.db_common import DbPinecone


class DeviceService(object):
    _index_name = ""
    _namespace = ""
    _db = None
    _es = None

    def __init__(self, namespace: str = "", index_name: str = "avl"):
        self._namespace = namespace
        self._index_name = index_name
        if not self._db:
            self._db = DbPinecone(index_name=index_name)
        if not self._es:
            self._es = es_conn

    def get_list(self, req: DeviceDetailReq) -> List[DeviceInfoSchema]:
        db = self._db
        if req.vector_id:
            meta_list = db.get_by_ids([req.vector_id])
        else:
            meta_list = db.get_by_text(req.device_name, req.gid)
        return [DeviceInfoSchema(**x) for x in meta_list]

    def get_detail(self, req: DeviceDetailReq) -> DeviceInfoSchema | None:
        # Notice 可以根据命名空间区分用户
        db = self._db
        if req.vector_id:
            meta_list = db.get_by_ids([req.vector_id])
        else:
            meta_list = db.get_by_text(req.device_name, req.gid)
        if not meta_list:
            return
        log.info(f"[DeviceService][get_detail] meta_list: {meta_list}")
        return DeviceInfoSchema(**meta_list[0])

    async def update_info(self, req: DeviceInfoSchema):
        """修改商品详情"""
        text = req.to_page_content()
        db = self._db
        # 检测是否存在
        detail = await self.get_detail(DeviceDetailReq(gid=req.gid, device_name=req.device_name))
        metadata = req.model_dump(by_alias=True, exclude=set("vector_id", ))
        if detail.vector_id != "":
            res = db.update_by_id(req.vector_id, text, metadata)
        else:
            res = db.batch_add([text], [metadata])
            # 更新数据库向量ID
            await GoodsDao.update_vector_id(int(req.gid), res[0])

        log.info(f"[DeviceService][update_info] res: {res}")
        return res

    async def abatch_add(self, texts: List[str], metadata: List[Dict], **kwargs) -> Dict:
        """批量添加"""
        db = self._db
        vector_ids = await db.abatch_add(texts, metadata, **kwargs)
        res = dict()
        for index, m in enumerate(metadata):
            vid = vector_ids[index]
            gid = int(m["g_id"])
            _ = await GoodsDao.update_vector_id(gid, vid)
        return res

    async def batch_delete(self, vector_ids: List[str], gids: List[int] = None) -> bool:
        """批量删除"""
        db = self._db
        res = True
        try:
            db.delete_by_ids(vector_ids, gids)
            # 去除关系数据库中向量ID
            _ = await GoodsDao.batch_delete_vector_id(gids)
            log.info(f"[GoodsService][batch_delete] complete, vector_ids: {vector_ids}")
        except Exception as e:
            res = False
            log.error(f"[GoodsService][batch_delete] error: {e}")
        return res
